let core = require('core');
import regeneratorRuntime from 'regenerator-runtime/runtime';
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
};

const formatTime2 = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-')
};

const formatTime3 = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month].map(formatNumber).join('-')
};

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
};

//
// 将 Date 转化为指定格式的String, date可以是int时间戳或 Date对象
// 月(m)、日(d)、小时(h)、分(i)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// formatDatetime(date, "yyyy-mm-dd hh:ii:ss.S") ==> 2006-07-02 08:09:04.423
// formatDatetime(date, "yyyy-m-d h:i:s.S")      ==> 2006-7-2 8:9:4.18
const formatDatetime = function(date, fmt) { //author: meizz
  if(!date) {
    return "";
  }
  if(!(date instanceof Date)) {
    if(/^\d+$/.test(date)) {
      date = (date+"").length>10 ? date : date*1000;
      date = new Date(parseInt(date));
    }else {
      date = new Date(date.replace(/-/g,'/'));
    }
  }
  var o = {
    "m+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "i+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    "S": date.getMilliseconds() //毫秒
  };
  var yearMatch = fmt.match(/(y+)/);
  if (yearMatch) {
    fmt = fmt.replace(yearMatch[0], (date.getFullYear() + "").substr(4 - yearMatch[0].length));
  }
  for (var k in o) {
    var match = fmt.match(new RegExp("(" + k + ")"));
    if (match)
      fmt = fmt.replace(match[0], (match[0].length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  }
  return fmt;
};

const getListItemIndexById = function(list, id) {
  if(!list || !id)
    return -1;
  for(var i=0;i<list.length;i++) {
    if(list[i].id==id) {
      return i;
    }
  }
  return -1;
}, getListItemById = function(list, id) {
  if(!list || !id)
    return null;
  for(var i=0;i<list.length;i++) {
    if(list[i].id==id) {
      return list[i];
    }
  }
  return null;
},
  getListItemAttrById = function(list, id, attrName, defaultValue='') {
    var item = getListItemById(list, id);
    if(item && item[attrName]) {
      return item[attrName];
    }
    return defaultValue;
  };

/**
 * 加载更多按钮功能
 * page.data定义moreButton(可由moreButtonDataField更改) moreButton.text作为按钮文本, moreButton.page作为页码
 * @param pageInstance
 * @param url 接口地址
 * @param queryData querystring parameters
 * @param moreButtonDataField morebutton data在page.data中的字段名
 * @param listFieldName 渲染的列表数据再page.data中的字段名
 * @param retDataFieldName 接口返回的列表数据再http response ret.data中的字段名
 * @param dataFormatter function, 处理服务器返回的列表数据，返回处理过后的数组, this指向pageInstance
 */
const fetch = function(pageInstance, url,queryData, moreButtonDataField, listFieldName, retDataFieldName, dataFormatter) {
  let moreButtonData = pageInstance.data[moreButtonDataField] || {page:1};
  if(moreButtonData.loading || moreButtonData.nomore) {
    return;
  }
  queryData.page = moreButtonData.page;
  pageInstance.setData({[moreButtonDataField+'.'+'loading']: true, [moreButtonDataField+'.'+'text']: '正在加载...'});
  core.get({
    url: url, data: queryData,
    success(ret, response) {
      let listData = retDataFieldName?ret.data[retDataFieldName]:ret.data;
      let listLength = listData.length;
      if(typeof dataFormatter === 'function') {
        listData = dataFormatter.apply(pageInstance, [listData, ret.data]) || listData;
      }else if(dataFormatter==='unique') {
        function uniqueFormatter(listData) {
          let formattedList = [];
          out:  for(let i in listData) {
            let item = listData[i];
            for(let j in pageInstance.data[listFieldName]) {
              let originItem = pageInstance.data[listFieldName][j];
              if(originItem.id==item.id) {
                continue out;
              }
            }
            formattedList.push(item);
          }
          return formattedList;
        }
        listData = uniqueFormatter(listData);
      }
      if(Array.isArray(listData) && listLength>0) {
        pageInstance.data[listFieldName] = (pageInstance.data[listFieldName]||[]).concat(listData);
        let pagesize = queryData.pagesize || 10;
        
        if(listLength<pagesize) {
          pageInstance.setData({
            [listFieldName]: pageInstance.data[listFieldName],
            [moreButtonDataField+'.'+'page']: moreButtonData.page + 1,
            [moreButtonDataField+'.'+'loading']: false,
            [moreButtonDataField+'.'+'nomore']: true,
            [moreButtonDataField+'.'+'text']: '没有更多'
          });
        }else {
          pageInstance.setData({
            [listFieldName]: pageInstance.data[listFieldName],
            [moreButtonDataField+'.'+'page']: moreButtonData.page + 1,
            [moreButtonDataField+'.'+'loading']: false,
            [moreButtonDataField+'.'+'text']: '加载更多'
          });
        }
      }else {
        let text = moreButtonData.page == 1 ? '暂无数据' : '没有更多';
        let nothing = moreButtonData.page == 1 ? true : false;
        console.log(nothing)
        pageInstance.setData({[listFieldName]: pageInstance.data[listFieldName]||[],[moreButtonDataField+'.'+'nomore']:true, [moreButtonDataField+'.'+'text']:text,[moreButtonDataField+'.'+'nothing']:nothing});
      }
    },
    fail(ret, response) {
      pageInstance.setData({
        [moreButtonDataField+'.'+'loading']: false,
        [moreButtonDataField+'.'+'text']: '加载更多',
      });
    }
  })
};
const getRemoteDataCached = async function(options) {
  let data, url = options.url, cacheKey = options.cacheKey, useCache = options.useCache===undefined ? true : options.useCache,
    retDataKey = options.dataKey;
  if(useCache) {
    data = core.getCache(cacheKey);
  }
  if(!data) {
    data = await (new Promise(function(resolve, reject) {
      core.get({
        url: url,
        data: options.data || '',
        loading:false,
        success(ret) {
          resolve(retDataKey ? ret.data[retDataKey]:ret.data);
        },
        fail(ret) {
          reject(ret);
        }
      });
    }));
    core.setCache(cacheKey, data, 1800);
  }
  return data;
};

/**
 * 获取可供选择的开放城市
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getSiteCities = async function (useCache=true) {
  let app = getApp();
  let cacheKey = 'site_cities';
  let siteCities;
  if(useCache) {
    siteCities = core.getCache(cacheKey);
  }

  if(!siteCities) {
    siteCities = await (new Promise(function(resolve, reject) {
      core.get({
        url:'/xilujob.site_city/site_cities',
        loading:false,
        success(ret) {
          resolve(ret.data);
        },
        fail(ret) {
          reject(ret);
        }
      });
    }));
    core.setCache(cacheKey, siteCities, 1800);
  }
  return siteCities;
};

/**
 * 获得可供选择的福利
 * @param {Boolean} useCache
 * @returns {Promise.<*>}
 */
const getBenefits = async function (useCache=true) {
  let cacheKey = 'benefit_list';
  let benefits;
  if(useCache) {
    benefits = core.getCache(cacheKey);
  }
  if(!benefits) {
    benefits = await (new Promise(function(resolve, reject) {
      core.get({
        url:'/xilujob.common/benefits',
        loading:false,
        success(ret) {
          resolve(ret.data);
        },
        fail(ret) {
          reject(ret);
        }
      });
    }));
    core.setCache(cacheKey, benefits, 1800);
  }
  return benefits;
};
/**
 *
 * @param {Boolean} excludeZero 是否排除id<=0的item
 * @param {Boolean} useCache
 * @returns {Promise.<*>}
 */
const getWorkExperienceOptions = async function (excludeZero=false, useCache=true) {
  let cacheKey = 'work_experience_options';
  let options;
  if(useCache) {
    options = core.getCache(cacheKey);
  }
  if(!options) {
    options = await (new Promise(function(resolve, reject) {
      core.get({
        url:'/xilujob.common/work_experience',
        loading:false,
        success(ret) {
          resolve(ret.data);
        },
        fail(ret) {
          reject(ret);
        }
      });
    }));
    core.setCache(cacheKey, options, 1800);
  }
  if(excludeZero) {
    let zeroIdIndex = null;
    for(let i in options) {
      if(options[i].id<=0) {
        zeroIdIndex = i;
        break;
      }
    }
    if(zeroIdIndex!==null) {
      options.splice(zeroIdIndex, 1);
    }
  }
  return options;
};

/**
 *
 * @param {Boolean} excludeZero 是否排除id<=0的item
 * @param {Boolean} useCache
 * @returns {Promise.<*>}
 */
const getEducationLevels = async function (excludeZero=false, useCache=true) {
  let cacheKey = 'education_levels';
  let levels;
  if(useCache) {
    levels = core.getCache(cacheKey);
  }
  if(!levels) {
    levels = await (new Promise(function(resolve, reject) {
      core.get({
        url:'/xilujob.common/education_levels',
        loading:false,
        success(ret) {
          resolve(ret.data);
        },
        fail(ret) {
          reject(ret);
        }
      });
    }));
    core.setCache(cacheKey, levels, 1800);
  }
  if(excludeZero) {
    let zeroIdIndex = null;
    for(let i in levels) {
      if(levels[i].id<=0) {
        zeroIdIndex = i;
        break;
      }
    }
    if(zeroIdIndex!==null) {
      levels.splice(zeroIdIndex, 1);
    }
  }
  return levels;
};
/**
 * 获取城市所有的区数据
 * @param {int|null} city_id 留空则使用当前城市
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getDistricts = function (city_id=null, useCache=true) {
  let app = getApp();
  if(!city_id) {
    city_id = app.getCurrentCity().id;
  }
  let cacheKey = 'city_districts_'+city_id;
  return getRemoteDataCached({
    url: '/xilujob.common/districts/city_id/' + city_id,
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};
/**
 * 获取省市区三级树状结构
 * @param {int} level 默认3层
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getAreasTree = async function (level=3,useCache=true) {
	let cacheKey = 'areas_tree';
	let areas;
	if(useCache) {
		areas = core.getCache(cacheKey);
	}
	if(!areas) {
		areas = await (new Promise(function(resolve, reject) {
		core.get({
		  url:'/xilujob.common/area_tree',
		  loading:false,
		  success(ret) {
			resolve(ret.data);
		  },
		  fail(ret) {
			reject(ret);
		  }
		});
	  }));
	  core.setCache(cacheKey, areas, 1800);
	}
	if(level==1) {
	  for(let i in areas) {
		delete areas[i].childlist;
	  }
	}else if(level==2) {
	  for(let i in areas) {
		let sendAreas = areas[i].childlist;
		for(let j in sendAreas) {
		  delete sendAreas[j].childlist;
		}
	  }
	}
	return areas;
  };
/**
 * 获取职位分类
 * @param {int} level 默认3层
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getJobCategories = async function (level=3,useCache=true) {
  let cacheKey = 'job_categories';
  let categories;
  if(useCache) {
    categories = core.getCache(cacheKey);
  }
  if(!categories) {
    categories = await (new Promise(function(resolve, reject) {
      core.get({
        url:'/xilujob.common/job_categories',
        loading:false,
        success(ret) {
          resolve(ret.data);
        },
        fail(ret) {
          reject(ret);
        }
      });
    }));
    core.setCache(cacheKey, categories, 1800);
  }
  if(level==1) {
    for(let i in categories) {
      delete categories[i].childlist;
    }
  }else if(level==2) {
    for(let i in categories) {
      let sendCategory = categories[i].chilidlist;
      for(let j in sendCategory) {
        delete sendCategory[j].childlist;
      }
    }
  }
  return categories;
};

/**
 * 获取薪资区间选项
 * @param {int} salaryType 1时薪,2日薪,3月薪
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getSalaryOptions = function (salaryType, useCache=true) {
  let app = getApp();
  let cacheKey = 'salary_options_type_'+salaryType;
  return getRemoteDataCached({
    url: '/xilujob.common/salary/type/' + salaryType,
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 职位举报类型选项
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getJobInformTypes = function (useCache=true) {
  let cacheKey = 'job_inform_types';
  return getRemoteDataCached({
    url: '/xilujob.common/job_inform_types',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 企业类型
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getCompanyTypes = function (useCache=true) {
  let cacheKey = 'company_types';
  return getRemoteDataCached({
    url: '/xilujob.common/company_properties',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 企业规模
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getCompanyScales = function (useCache=true) {
  let cacheKey = 'company_scales';
  return getRemoteDataCached({
    url: '/xilujob.common/company_scales',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 企业行业
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getIndustryCategories = function (useCache=true) {
  let cacheKey = 'industry_categories';
  return getRemoteDataCached({
    url: '/xilujob.common/industry_categories',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 求职状态
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getWorkStates = function (useCache=true) {
  let cacheKey = 'work_states';
  return getRemoteDataCached({
    url: '/xilujob.common/work_states',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 简历个人标签选项
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getResumePersonalTags = function (useCache=true) {
  let cacheKey = 'resume_personal_tags';
  return getRemoteDataCached({
    url: '/xilujob.common/resume_personal_tags',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 简历专业技能精通程度选项
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getSkillLevels = function (useCache=true) {
  let cacheKey = 'skill_levels';
  return getRemoteDataCached({
    url: '/xilujob.common/skill_levels',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 评论标签选项
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getCommentTags = function (useCache=true) {
  let cacheKey = 'comment_tags';
  return getRemoteDataCached({
    url: '/xilujob.common/comment_tags',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 获取区数据，包含下级
 * @param {int} cityId 城市id
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 */
const getAreas = function (cityId='',useCache=true) {
  if(!cityId)
    cityId = getApp().getCurrentCity().id;
  let cacheKey = 'districts_with_'+cityId;
  return getRemoteDataCached({
    url: '/xilujob.common/districts_with',
    data: {city_id:cityId},
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 获取城市数据，包含省份
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 */
const getCities = function (useCache=true) {
  let cacheKey = 'province_city';
  return getRemoteDataCached({
    url: '/xilujob.common/province_city',
    data: {},
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};


module.exports = {
  formatTime: formatTime, formatDatetime,
  formatTime2: formatTime2,
  formatTime3: formatTime3,
  getListItemIndexById, getListItemById, getListItemAttrById, fetch: fetch,
  getSiteCities, getBenefits, getWorkExperienceOptions, getEducationLevels, getDistricts, getJobCategories,
  getSalaryOptions, getJobInformTypes, getCompanyTypes, getCompanyScales, getIndustryCategories, getWorkStates,
  getResumePersonalTags, getCommentTags, getSkillLevels,
  getAreas,getAreasTree,
  getCities,
};
